package com.itheima.jdbc;

import org.junit.Test;

import java.sql.*;

public class JdbcDemo_PreparedStatement {

    /**
     * 防SQL 注入
     * @throws Exception
     */
    @Test
    public void test_login() throws Exception {

        //注册驱动  5.5版本后可以省略
        Class.forName("com.mysql.jdbc.Driver");

        //获取连接
        String url = "jdbc:mysql://47.100.230.149:3306/myheima";
        String username = "myheima";
        String password = "myheima";

        Connection conn = DriverManager.getConnection(url, username, password);

        //定义sql
        String uname = "zhangsan";
        String pwd = "'or 1 = 1'";
        String sql = "SELECT * FROM tb_user WHERE username = ? AND password = ? ";

        //获取sql执行对象
        PreparedStatement psmt = conn.prepareStatement(sql);
        psmt.setString(1,uname);
        psmt.setString(2,pwd);

        //执行sql
        ResultSet rs = psmt.executeQuery();

        //处理结果
        if(rs.next()){
            System.out.println("登陆成功");
        }else {
            System.out.println("登录失败");
        }

        //释放资源
        rs.close();
        psmt.close();
        conn.close();
    }

    /**
     * SQL 注入
     * @throws Exception
     */
    @Test
    public void test_login_project() throws Exception {

        //注册驱动  5.5版本后可以省略
        Class.forName("com.mysql.jdbc.Driver");

        //获取连接
        String url = "jdbc:mysql://47.100.230.149:3306/myheima";
        String username = "myheima";
        String password = "myheima";

        Connection conn = DriverManager.getConnection(url, username, password);

        //定义sql
        String uname = "zhangsan";
        String pwd = "'or '1' = '1";
        String sql = "SELECT * FROM tb_user WHERE username = '"+ uname + "' AND password = '"+ pwd + "'";
        System.out.println(sql);

        //获取sql执行对象
        Statement statement = conn.createStatement();

        //执行sql
        ResultSet rs = statement.executeQuery(sql);

        //处理结果
        if(rs.next()){
            System.out.println("登陆成功");
        }else {
            System.out.println("登录失败");
        }

        //释放资源
        statement.close();
        conn.close();
    }
}
